<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="请输入关键字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
    	<!-- sortable="custom"  -->
      <el-table-column label="编号" prop="id" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="直营店名称" prop="storeName" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.storeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" prop="storeAddress" align="center" width="240">
        <template slot-scope="scope">
          <span>{{ scope.row.storeAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在地" prop="storeLocation" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.storeLocation }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" prop="storeContacts" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.storeContacts }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人手机号" prop="storeContactsPhone" align="center" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.storeContactsPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加入日期" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号" align="center" width="95">
        <template slot-scope="scope">
          <span v-if="scope.row.sys_users[0] && scope.row.sys_users[0].userName">{{ (scope.row.sys_users[0] || {}).userName }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="goToDetail(scope.row)">查看</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button type="warning" size="mini" @click="handleReset(scope.row)">重置</el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handleDelete(scope.row)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 560px; margin-left:0px;">
        <el-form-item label="直营店名称" prop="storeName">
          <el-input v-model="temp.storeName" />
        </el-form-item>
        <el-form-item label="直营店图片" prop="fileList">
          <el-upload :file-list="temp.fileList" :action="host+'/admin/img/1'" :headers="headers" :limit="1" :on-success="handleSuccess" accept="image/png, image/jpeg" class="upload-demo" list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="直营店简介" prop="storeDesc">
          <el-input :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.storeDesc" type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="直营店经纬度" prop="storeXY">
          <el-input v-model="temp.storeXY" />
          <!--<label>关键词：<input v-model="keyword"></label>-->
            <label>查找地址(点击地址获取经纬度)：<el-input style="width: 300px" v-model="keyword" /></label>
            <baidu-map ref="map" class="bm-view" @click="getAddressIp">
                <bm-view class="map"></bm-view>
                <bm-local-search  :keyword="keyword" map-type="BMAP_NORMAL_MAP" :auto-viewport="true" ></bm-local-search>
                <!--<bm-local-search :keyword="keyword" :auto-viewport="true" :location="location"></bm-local-search>-->
            </baidu-map>
          <!--<bm-local-search ref="map" :keyword="keyword" :auto-viewport="true" :location="location"></bm-local-search>-->
          <!--<baidu-map  :center="center" :zoom="zoom" :scroll-wheel-zoom="true" class="bm-view" map-type="BMAP_NORMAL_MAP" @click="getAddressIp" />-->
        </el-form-item>
        <el-form-item label="直营店地址" prop="storeAddress">
          <el-input v-model="temp.storeAddress" />
        </el-form-item>
        <el-form-item label="直营店负责人" prop="storeContacts">
          <el-input v-model="temp.storeContacts" />
        </el-form-item>
        <el-form-item label="负责人手机" prop="storeContactsPhone">
          <el-input v-model="temp.storeContactsPhone" />
        </el-form-item>
        <el-form-item label="所在地" prop="storeLocation">
          <el-input v-model="temp.storeLocation" />
        </el-form-item>
        <el-form-item label="账号昵称" prop="storeAccount">
          <el-input v-model="temp.storeAccount" />
        </el-form-item>
        <el-form-item label="直营店状态" prop="storeStatus">
          <el-select v-model="temp.storeStatus" style="width: 100%;" class="filter-item">
            <el-option v-for="item in statusOptions1" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogDetailVisible" title="查看" width="80%">
      <el-card>
        <div style="text-align: center;font-size: 18px;">
          总用户：{{storeInfo.userCount}}人 待分配：{{storeInfo.waitCount}}人 在职：{{storeInfo.workCount}}人
        </div>
        <div style="margin-bottom: 5px;">下属员工</div>
        <el-table v-loading="listLoading" :key="tableKey1" :data="userList" border fit highlight-current-row style="width: 100%;">
          <el-table-column label="编号" type="index" align="center" width="60" />
          <el-table-column label="昵称" prop="userNickName" align="center" />
          <el-table-column label="真实姓名" prop="userName" align="center" />
          <el-table-column :formatter="formatSex" label="性别" prop="userSex" align="center" width="80" />
          <el-table-column label="手机号" prop="userPhone" align="center" />
          <el-table-column label="来源" prop="userSource" align="center" />
          <el-table-column label="生日" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.userBirthday }}</span>
            </template>
          </el-table-column>
          <el-table-column :formatter="formatStatus" label="用户状态" prop="rdd_user_statuses" align="center" />
          <el-table-column label="所属公司" align="center">
          	 <template slot-scope="scope">
              <span>{{ ((scope.row.rdd_user_statuses[0] || {}).rdd_company || {}).companyName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" v-if="scope.row.rdd_user_statuses.length && scope.row.rdd_user_statuses[0].userStatus==1" @click="handleDistribute(scope.row)">分配</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="totalDialog>0" :total="totalDialog" :page.sync="listDialogQuery.pageNum" :limit.sync="listDialogQuery.pageSize" @pagination="getlistDialogList" />
      </el-card>
      <el-card class="box-card row-box">
        <span class="row-title">直营店信息</span>
        <el-form ref="dataForm1" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="直营店名称">
            <span>{{ temp.storeName }}</span>
          </el-form-item>
          <el-form-item label="直营店图片">
            <img :src="temp.storeImg" style="max-width: 150px;max-height: 150px;">
          </el-form-item>
          <el-form-item label="直营店简介">
            <span>{{ temp.storeDesc }}</span>
          </el-form-item>
          <el-form-item label="直营店地址">
            <span>{{ temp.storeAddress }}</span>
          </el-form-item>
          <el-form-item label="直营店负责人">
            <span>{{ temp.storeContacts }}</span>
          </el-form-item>
          <el-form-item label="负责人手机">
            <span>{{ temp.storeContactsPhone }}</span>
          </el-form-item>
          <el-form-item label="所在地">
            <span>{{ temp.storeLocation }}</span>
          </el-form-item>
          <el-form-item label="账号昵称">
            <span>{{ temp.storeAccount }}</span>
          </el-form-item>
          <el-form-item label="直营店状态">
            <span>{{ temp.storeStatus | filterStoreStatus }}</span>
          </el-form-item>
            <el-form-item label="推荐二维码">
                <img :src="shopQr" style="width: 200px; height: 200px;">
                <a :href="shopQr" :download=temp.storeName>下载二维码</a>
            </el-form-item>
        </el-form>
      </el-card>
      <el-dialog :visible.sync="innerVisible" title="分配公司" append-to-body width="30%">
        <el-form ref="dataForm2" label-position="right" label-width="100px">
          <el-form-item label="选择公司">
            <el-select filterable v-model="chooseCompany.company_id" style="width: 200px" class="filter-item">
	            <el-option v-for="item in companyOptions" :key="item.key" :label="item.value" :value="item.key" />
	        </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">{{ $t('table.cancel') }}</el-button>
          <el-button type="primary" @click='distributeFactory'>{{ $t('table.confirm') }}</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import {
	fetchShopList,
	fetchQrCode,
	createShop,
	updateShop,
	delShop,
	getShopUser,
	resetPwd
} from "@/api/shop";
import { fetchEnterPriseListAjax } from "@/api/enterprise";
import { distributeFactory } from "@/api/userList";
import waves from "@/directive/waves"; // Waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
// import BaiduMap from "vue-baidu-map/components/Map/Map.vue";
// import BmGeolocation from "vue-baidu-map/components/controls/Geolocation.vue";

const calendarTypeOptions = [
	{ key: "CN", display_name: "China" },
	{ key: "US", display_name: "USA" },
	{ key: "JP", display_name: "Japan" },
	{ key: "EU", display_name: "Eurozone" }
];

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
	acc[cur.key] = cur.display_name;
	return acc;
}, {});

export default {
	name: "ComplexTable",
	components: { Pagination },
	directives: { waves },
	filters: {
		statusFilter(status) {
			const statusMap = {
				published: "success",
				draft: "info",
				deleted: "danger"
			};
			return statusMap[status];
		},

		typeFilter(type) {
			return calendarTypeKeyValue[type];
		},

		filterStoreStatus(value) {
			return 	value === 0 ? '未确认' : '已确认';
		}
	},
	data() {
		return {
            keyword: '南京',
            shopQr:'',
			tableKey: 0,
			tableKey1: 0,
			list: null,
			userList: [],
			total: 0,
			listLoading: true,
			listQuery: {
				pageNum: 1,
				pageSize: 20,
				importance: undefined,
				title: undefined,
				type: undefined,
				storeType: "0",
				sort: "请选择直营店类型"
			},
			listDialogQuery: {
				pageNum: 1,
				pageSize: 20
			},
			// importanceOptions: [1, 2, 3],
			calendarTypeOptions,
			sortOptions: [
				{ label: "全部", key: "0" },
				{ label: "加盟店", key: "1" },
				{ label: "直营店", key: "2" }
			],
			statusOptions: ["published", "draft", "deleted"],
			showReviewer: false,
			temp: {
				id: undefined,
				importance: 1,
				remark: "",
				timestamp: new Date(),
				title: "",
				type: "",
				status: "published",
				storeXY: ""
			},
			dialogFormVisible: false,
			dialogStatus: "",
			textMap: {
				update: "编辑",
				create: "新增直营店"
			},
			rules: {
				storeName: [
					{
						required: true,
						message: "直营店名称必填",
						trigger: "change"
					}
				],
				storeContacts: [
					{
						required: true,
						message: "直营店负责人必填",
						trigger: "change"
					}
				],
				storeAddress: [
					{
						required: true,
						message: "直营店地址必填",
						trigger: "change"
					}
				],
				storeContactsPhone: [
					{
						required: true,
						message: "负责人手机必填",
						trigger: "change"
					}
				],
				storeDesc: [
					{
						required: true,
						message: "直营店简介必填",
						trigger: "change"
					}
				],
				storeXY: [
					{
						required: true,
						message: "直营店经纬度必填",
						trigger: "change"
					}
				],
				storeLocation: [
					{
						required: true,
						message: "所在地必填",
						trigger: "change"
					}
				],
				storeAccount: [
					{
						required: true,
						message: "账号昵称必填",
						trigger: "change"
					}
				],
				storeStatus: [
					{
						required: true,
						message: "直营店状态必填",
						trigger: "change"
					}
				]
			},
			downloadLoading: false,
			center: { lng: 118.78, lat: 32.07 },
			zoom: 15,
			headers: {
				Authorization: "Bearer " + this.$store.state.user.token
			},
			host: process.env.BASE_API,
			dialogDetailVisible: false,
			totalDialog: 0,
			innerVisible: false,
			chooseCompany: {
				user_id: null,
				company_id: null
			},
			companyOptions: [],
			statusOptions1: [{
				key: 0,
				label: '未确认'
			}, {
				key: 1,
				label: '已确认'
			}],
			storeInfo: {},
		};
	},
	created() {
		this.getList();
		this.getEnterPriseOptions();
	},

	methods: {
		async goToDetail(row) {
			this.listDialogQuery.id = row.id;
			const res = await getShopUser(this.listDialogQuery);
			if(res.data.code == 0) {
				this.storeInfo = res.data.data.storeInfo;
				this.userList = res.data.data.userData.pageData;
				this.totalDialog = res.data.data.userData.maxCount;
			}
			this.temp = Object.assign({}, row); // copy obj
			this.dialogDetailVisible = true;
            const qrInfo = await fetchQrCode(this.temp.id);
            this.shopQr = 'data:image/jpeg;base64,'+qrInfo.data.data
		},

		async getEnterPriseOptions() {
			const res = await fetchEnterPriseListAjax();
			res.data.data.forEach(item => {
				this.companyOptions.push({
					key: item.id,
					value: item.companyName
				});
			});
		},

		async distributeFactory() {
			const res = await distributeFactory(this.chooseCompany);
			const res1 = await getShopUser(this.temp);
			if(res1.data.code == 0) {
				this.userList = res1.data.data;
			}
			this.innerVisible = false;
		},

		handleSuccess(file, fileList) {
			this.temp.fileList = [];
			this.temp.fileList.push({
				name: fileList.name,
				url: file.data.file
			});
		},

		mapHandler({ BMap, map }) {
			const _this = this;

			const geolocation = new BMap.Geolocation();

			geolocation.getCurrentPosition(
				function(r) {
					console.log(r);

					_this.center = { lng: r.longitude, lat: r.latitude }; // 设置center属性值

					_this.autoLocationPoint = {
						lng: r.longitude,
						lat: r.latitude
					}; // 自定义覆盖物

					_this.initLocation = true;

					console.log("center:", _this.center); // 如果这里直接使用this是不行的
				},
				{ enableHighAccuracy: true }
			);
		},
		getAddressIp(e) {
			const pt = e.point;
			this.$set(this.temp, "storeXY", pt.lng + "," + pt.lat);
		},
		getList() {
			this.listLoading = true;
			fetchShopList(this.listQuery).then(response => {
				this.list = response.data.data.pageData;
				this.total = response.data.data.maxCount;
				// Just to simulate the time of the request
				setTimeout(() => {
					this.listLoading = false;
				}, 0.8 * 1000);
			});
		},
		handleFilter() {
			this.listQuery.pageNum = 1;
			this.getList();
		},

		handleDelete(row) {
			this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				this.handleDeleteAjax(row.id);
			}).catch(() => {
				return;
			});
		},

		async handleDeleteAjax(id) {
			const req = {
				id: id
			};
			const res = await delShop(req);
			if (res.data.code === 0) {
				this.handleFilter();
				this.$notify({
					title: "成功",
					message: "删除成功",
					type: "success",
					duration: 2000
				});
			}
		},

		handleModifyStatus(row, status) {
			this.$message({
				message: "操作成功",
				type: "success"
			});
			row.status = status;
		},

		sortChange(data) {
			const { prop, order } = data;
			if (prop === "id") {
				this.sortByID(order);
			}
		},
		sortByID(order) {
			if (order === "ascending") {
				this.listQuery.sort = "+id";
			} else {
				this.listQuery.sort = "-id";
			}
			this.handleFilter();
		},
		resetTemp() {
			this.temp = {
				id: undefined,
				importance: 1,
				remark: "",
				timestamp: new Date(),
				title: "",
				status: "published",
				type: "",
				storeXY: ''
			};
		},
		handleCreate() {
			this.resetTemp();
			this.dialogStatus = "create";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
		},
		createData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					this.temp.storeImg = this.temp.fileList[0].url;
					this.temp.storeType = "0";
					createShop(this.temp).then(() => {
						this.list.unshift(this.temp);
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "创建成功",
							type: "success",
							duration: 2000
						});
						this.handleFilter();
					});
				}
			});
		},
		handleUpdate(row) {
			row.fileList = [
				{
					url: row.storeImg
				}
			];
			this.temp = Object.assign({}, row); // copy obj
			this.temp.timestamp = new Date(this.temp.timestamp);
			this.dialogStatus = "update";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
		},

		updateData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					this.temp.storeImg = this.temp.fileList[0].url;
					const tempData = Object.assign({}, this.temp);
					tempData.timestamp = +new Date(tempData.timestamp);
					updateShop(tempData).then(() => {
						for (const v of this.list) {
							if (v.id === this.temp.id) {
								const index = this.list.indexOf(v);
								this.list.splice(index, 1, this.temp);
								break;
							}
						}
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "更新成功",
							type: "success",
							duration: 2000
						});
					});
				}
			});
		},

		formatJson(filterVal, jsonData) {
			return jsonData.map(v =>
				filterVal.map(j => {
					if (j === "timestamp") {
						return parseTime(v[j]);
					} else {
						return v[j];
					}
				})
			);
		},

		handleDistribute(row) {
			this.innerVisible = true;
			this.chooseCompany.user_id = row.id;
			this.chooseCompany.company_id = null;
		},

		formatSex(row) {
			return row.brokerSex === 0 ? "男" : "女";
		},

		formatStatus(row) {
			if (row.rdd_user_statuses.length > 0) {
				const arr = ["待分配", "待入职", "待确认", "在职", "离职"];
				return arr[row.rdd_user_statuses[0].userStatus];
			}
			return '-'
		},

		async getlistDialogList() {
			const res = await getShopUser(this.listDialogQuery);
			if(res.data.code == 0) {
				this.userList = res.data.data.pageData;
				this.totalDialog = res.data.data.maxCount;
			}
		},

		handleReset(row) {
			this.$confirm("将重置密码为原始密码, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				this.handleResetAjax(row)
			}).catch(() => {
				return
			});
		},

		async handleResetAjax(row) {
			let res = await resetPwd({
				id: row.sys_users[0].id
			});
			if(res.data.code == 0) {
				row.sys_users[0].userLoginPwd = row.sys_users[0].userLoginName;
				this.$notify({
					title: "成功",
					message: "重置成功",
					type: "success",
					duration: 2000
				});
			}
		}
	}
};
</script>
<style scoped>
    .el-dialog{
        width: 70%;
    }
    .bm-view .map{
        height: 300px;
    }
    .bm-view>div:last-child{
        position: absolute;
        top: 72px;
        z-index: 1000;
        left: 305px;
        width: 200px;
    }
    .bm-view {
        width: 300px;
        height: 300px;
    }
</style>
